package com.t4.courseware.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.t4.courseware.common.Result;
import com.t4.courseware.handler.UserThreadLocal;
import com.t4.courseware.mapper.CoursewareMapper;
import com.t4.courseware.mapper.ExchangeMapper;
import com.t4.courseware.mapper.UserCoursewareMapper;
import com.t4.courseware.pojo.Courseware;
import com.t4.courseware.pojo.Exchange;
import com.t4.courseware.pojo.Order;
import com.t4.courseware.pojo.UserCourseware;
import com.t4.courseware.pojo.dto.UserDto;
import com.t4.courseware.service.ExchangeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ExchangeServiceImpl extends ServiceImpl<ExchangeMapper, Exchange> implements ExchangeService {

    @Resource
    private ExchangeMapper exchangeMapper;

    @Resource
    private UserCoursewareMapper userCoursewareMapper;

    @Resource
    private CoursewareMapper coursewareMapper;

    @Override
    public Result exchangeKey(String key) {
        Exchange exchange = exchangeMapper.selectOne(new LambdaQueryWrapper<Exchange>().eq(Exchange::getExchangeKey, key));
        if(exchange == null){
            return Result.SUCCESS(false);
        }
        Long cwId = exchange.getCwId();
        UserDto userDto = UserThreadLocal.get();
        UserCourseware userCourseware = userCoursewareMapper.selectOne(Wrappers.<UserCourseware>lambdaQuery().eq(UserCourseware::getUserId, userDto.getId()).eq(UserCourseware::getCwId, cwId));
        Courseware courseware = coursewareMapper.selectOne(Wrappers.<Courseware>lambdaQuery().eq(Courseware::getUploadUserId, userDto.getId()).eq(Courseware::getId, cwId));
        if (userCourseware == null && courseware == null) {
            UserCourseware userCourseware1 = new UserCourseware();
            userCourseware1.setCwId(cwId);
            userCourseware1.setUserId(userDto.getId());
            userCoursewareMapper.insert(userCourseware1);
            return Result.SUCCESS(true);
        }else {
            return Result.SUCCESS(false);
        }
    }
}
